package com.cykj.filters;

import com.alibaba.fastjson.JSON;
import com.cykj.dto.ResponseDTO;
import com.cykj.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;


@Component
public class LoginFilter implements GlobalFilter {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override // 过滤器
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 设置白名单
        String[] urlWhite = {
                "/user/login",
                "/user/register",
                "/admin/login",
                "/good/buyGood"
        };
        // 判断是否在白名单中，如果在，则放行，如果不在，进一步判断;
        String url = exchange.getRequest().getURI().getPath();
        for (String s : urlWhite) {
            if (s.equals(url)) {
                System.out.println("在白名单内...");
                return chain.filter(exchange); // 放行
            }
        }
        System.out.println("未在白名单内...");
        // 获取请求头里面的X-Token ==> 如果没有或者过期就提示，否则就放行
        List<String> strings = exchange.getRequest().getHeaders().get("X-Token");
        String token = "";
        if (strings != null && !strings.isEmpty()) {
            token = strings.get(0);
        }
        // 判断token是否存在
        if (token.isEmpty()) {
            return handleUnauthorized(exchange, ResponseDTO.error(-1, "请求未携带 token"));
        }
        // 判断 redis 是否含有  token 的 key
        if (Boolean.FALSE.equals(redisTemplate.hasKey(token))){
            return handleUnauthorized(exchange,ResponseDTO.error(-2,"token 无效")); // token 已过期
        }
        try {
            JwtUtils.parseJWT(token); // token 真的过期了
        } catch (Exception e) {
            return handleUnauthorized(exchange,ResponseDTO.error(-3,"token 已过期"));
        }
        // 更新 redis 的有效期
        redisTemplate.opsForValue().set(token, Objects.requireNonNull(redisTemplate.opsForValue().get(token)), 30, TimeUnit.MINUTES);
        // 放行
        return chain.filter(exchange);
    }

    // 添加处理未授权访问的方法
    private Mono<Void> handleUnauthorized(ServerWebExchange exchange, ResponseDTO responseDTO) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        byte[] bytes = JSON.toJSONString(responseDTO).getBytes(StandardCharsets.UTF_8);
        return response.writeWith(Mono.just(response.bufferFactory().wrap(bytes)));
    }

}
